"""
    自动化架构体系
    数据驱动运行入口
    Powered By Mr.shuhao
"""
from HTTP.FotorKeys import HTTP
from common.NewExcel import *
from common import logger,config
import inspect,time
from common.txt import Txt
from common.mysql import Mysql
from common.excelresult import Res
from common.mail import Mail

logger.info('==============开始运行==============')

def getfunc(obj, method):
    """
    反射获取函数和方法
    :param obj:对象
    :param method:方法名
    :return:
    """
    try:
        func = getattr(obj, method)
    except Exception as e:
        return None
    arg = inspect.getfullargspec(func).__str__()
    arg = arg[arg.find('args=') + 5:arg.find(', varargs')]
    arg = eval(arg) # 转成python可识别
    arg.remove('self')
    return func, len(arg)

def runcase(obj,line):
    if len(line[0]) > 0 or len(line[1])> 0: # 第一列或者第二列有内容,就不执行
        return # 分组信息不执行

    func = getfunc(obj,line[3]) # 第四列有内容,即关键字列

    if func is None:
        logger.warn('关键字{}不存在'.format(line[3]))
        print(line)
        return

    if func[1] == 0:
        func[0]()
    elif func[1] == 1:
        func[0](line[4])
    elif func[1] == 2:
        func[0](line[4], line[5])
    elif func[1] == 3:
        func[0](line[4], line[5], line[6])
    else:
        logger.warn("关键字暂不支持超过3个参数")

# 初始化配置
config.get_config('./lib/conf/conf.properties')
# 初始化数据库
mysql = Mysql()
mysql.init_mysql('./lib/conf/userinfo.sql')

casename = 'HTTP接口测试用例'

reader = Reader()
reader.open_excel('./lib/%s.xlsx' % casename)
writer = Writer()
writer.copy_open('./lib/%s.xlsx' % casename, './lib/result-%s.xlsx' % casename)
sheetname = reader.get_sheets()
# 写开始时间
starttime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
writer.set_sheet(sheetname[1])
writer.write(1,3,starttime)

# 运行的实例对象，默认是HTTP
http = HTTP(writer)
web = Web(writer)
app = App(writer)
obj = http

for sheet in sheetname:
    # 设置当前读取的sheet页面
    reader.set_sheet(sheet)
    writer.set_sheet(sheet)

    # openpyxl(Newexcel库)
    lines = reader.readline()

    # 分用例类型执行
    line = lines[1]
    if line[1] == "HTTP":
        obj = http
    elif line[1] == "WEB":
        obj = web
    elif line[1] == "APP":
        obj = app

    for i in range(reader.rows):
            obj.row = i
            line = lines[i]
            logger.info(line)
            runcase(obj, line)

# 写结束时间
endtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
writer.set_sheet(writer.get_sheets()[0])
writer.write(1,4,endtime)
writer.save_close()

# 获取结果数据
res = Res()
summary = res.get_res('./lib/result-%s.xlsx' % casename)
logger.info(summary)
groups = res.get_groups('./lib/result-%s.xlsx' % casename)
logger.info(groups)

txt = Txt('./lib/conf/' + config.config['mailtxt'])
html = txt.read()[0]

# 替换汇总信息
for key in summary.keys():
    if summary[key]=="Pass":
        html = html.replace('<td height="28" bgcolor="#FFFFFF" align="center" style="border:1px solid #ccc;">status</td>',
                     '<td height="28" bgcolor="#FFFFFF" align="center" style="border:1px solid #ccc;color:blue;">Pass</td>')
    elif summary[key]=="Fail":
        html = html.replace('<td height="28" bgcolor="#FFFFFF" align="center" style="border:1px solid #ccc;">status</td>',
                     '<td height="28" bgcolor="#FFFFFF" align="center" style="border:1px solid #ccc;color:red;">Fail</td>')
    else:
        html = html.replace(key,summary[key])
# 获取分组显示
tr = '<tr><td width="100" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">分组信息</td><td width="80" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">用例总数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">通过数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">状态</td></tr>'
trs = ""
for i in range(len(groups)):
    tmp = tr.replace('分组信息',str(groups[i][0]))
    tmp = tmp.replace('用例总数', str(groups[i][1]))
    tmp = tmp.replace('通过数', str(groups[i][2]))
    tmp = tmp.replace('状态', str(groups[i][3]))
    trs += tmp

# 读取配置,发送测试报告邮件
html = html.replace('mailbody',trs)
mail = Mail()
mail.send(html)





